package com.three.servie.implement;

import com.three.mapper.StudentMapper;
import com.three.pojo.Student;
import com.three.servie.AvatarService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOError;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Service
public class AvatarServiceImpl implements AvatarService {
    @Autowired
    StudentMapper userMapper;
    private static final String currentPath = System.getProperty("user.dir");


    @Override
    public void getAvatar(String id, HttpServletResponse response) throws IOException {
        Student student = new Student();
        student.setId(id);
        Student result = userMapper.select(student);
        if (result == null) {
            return;
        }
        String fileName = result.getAvatarName();
        if (fileName == null) {
            fileName = "default_avatar.png";
        }
        // Paths.get 拼接路径
        String filePath = Paths.get( currentPath,"media", "avatar", fileName).toString();
        // 1. 将图片文件加载到 Java 程序中
        File imageFile = new File(filePath);
        BufferedImage image = ImageIO.read(imageFile);
        // 2. 将图片转换为字节数组
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", baos);
        byte[] imageData = baos.toByteArray();
        // 3. 设置响应的内容类型和长度，并将字节数组作为响应的内容返回给前端
        response.setContentType("image/png");
        response.setContentLength(imageData.length);
        response.getOutputStream().write(imageData);
    }

    @Override
    public boolean postAvatar(String id, MultipartFile file) throws IOException {
        int index = file.getOriginalFilename().lastIndexOf(".");
        String extname = file.getOriginalFilename().substring(index);
        String filename = UUID.randomUUID() + extname;
        Path fullPath = Paths.get(currentPath, "media", "avatar", filename);
        // 获取拼接后的完整路径
        file.transferTo(new File(fullPath.toString()));  // 保存到磁盘中

        Student student = new Student();  // 构造一个用户对象
        student.setId(id);
        student.setAvatarName(filename);
        int c = userMapper.update(student);  // 更新数据库
        return c > 0;
    }
}
